import { UPLOADS_DIR } from "$lib/utils/paths";
import fs from "fs";
import path from "path";

export async function GET({ params }) {
  let { filename } = params;
  let filePath = path.join(UPLOADS_DIR, filename);
  if (!fs.existsSync(filePath)) {
    const [nameOnly] = filename.split(".");
    const found = fs.readdirSync(UPLOADS_DIR).find((f) => f.split(".")[0] === nameOnly);
    if (found) {
      filename = found;
      filePath = path.join(UPLOADS_DIR, found);
    }
  }
  if (!fs.existsSync(filePath)) { return new Response("File not found", { status: 404 }); }
  const fileStream = fs.createReadStream(filePath);
  const encodedFilename = encodeURIComponent(filename);
  return new Response(fileStream, { headers: { "Content-Type": "application/octet-stream", "Content-Disposition": `attachment; filename*=UTF-8''${encodedFilename}` } });
}
